package com.chanyachting.emall.action.aboutPage;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.chanyachting.emall.domain.Channel;
import com.chanyachting.emall.domain.Newsactivity;
import com.chanyachting.emall.form.NewsActivityForm;
import com.chanyachting.emall.service.ChannelService;
import com.chanyachting.emall.service.NewsActivityService;
import com.chanyachting.emall.serviceImpl.ChannelServiceImpl;
import com.chanyachting.emall.serviceImpl.NewsActivityServiceImpl;

public class QueryOneAboutAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		NewsActivityForm naForm = (NewsActivityForm) form;
		NewsActivityService naservice=new NewsActivityServiceImpl();
		ChannelService cService = new ChannelServiceImpl();
		
		int channelId = naForm.getChannelId();
		
		Channel c = new Channel(channelId);
		
		Integer tmpPri = 18;   //关于我们频道的优先度
		if (!tmpPri.equals(c.getPri())) {
			return mapping.findForward("error");
		}
		List<Channel> subChannelList = cService.getSubChannel(c);
		
		if (subChannelList == null || subChannelList.size() == 0) {
			return mapping.findForward("error");
		}
		Integer subChannelId = naForm.getSubChannelId();
		if (subChannelId == null) {
			subChannelId = subChannelList.get(0).getId();
			naForm.setSubChannelName(subChannelList.get(0).getName());
		} else {
			//判断指定的sub频道是否存在
			boolean isExistSubChannel = false;
			for(Channel cn:subChannelList) {
				if (cn == null || cn.getId() == null) {
					continue;
				}
				if (cn.getId().equals(subChannelId)) {
					naForm.setSubChannelName(cn.getName());
					isExistSubChannel = true;
					break;
				}
			}
			if (isExistSubChannel == false) {
				return mapping.findForward("error");
			}
		}
		
		List<Newsactivity> newsList = naservice.getNewsBySubChannalId(subChannelId.toString(), 1, 1, true);
		
		if (newsList == null || newsList.size() ==0) {
			return mapping.findForward("error");
		}
		
		naForm.setNews(newsList.get(0));
		naForm.setSubChannelList(subChannelList);
		naForm.setChannelId(channelId);
		naForm.setSubChannelId(subChannelId);
		naForm.setChannelName(c.getName());
		
		return mapping.findForward("gotoAboutPage");
	}
}
